package com.ptswitch.material.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Hibernate;
import org.hxzon.project.AbstractModelService;
import org.springframework.stereotype.Service;

import com.ptswitch.material.model.security.Permission;
import com.ptswitch.material.service.PermissionService;
import com.ptswitch.material.util.security.PermissionUtil;

@Service
public class PermissionServiceImpl extends AbstractModelService<Permission> implements PermissionService {

    @Override
    public void initPermissions() {
        List<Permission> dbPermissions = dao.list(Permission.class, -1, -1);
        Map<Long, Permission> dbPermissionMap = new HashMap<Long, Permission>();
        for (Permission p : dbPermissions) {
            dbPermissionMap.put(p.getId(), p);
        }
        List<Permission> newPermissions = new ArrayList<Permission>();
        for (Permission p : PermissionUtil.permissions) {
            Permission dbP = dbPermissionMap.get(p.getId());
            if (dbP == null) {
                newPermissions.add(p);
            } else {
                p.setDisplayName(dbP.getDisplayName());
            }
        }
        dao.addAll(newPermissions);
    }

    @Override
    public Permission findById(long id) {
        return PermissionUtil.find(id);
    }

    @Override
    public Permission findByIdWithRoles(long id) {
        Permission result = dao.oneById(Permission.class, id);
        if (result != null) {
            Hibernate.initialize(result.getRolePermissions());
        }
        return result;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Permission> findAllWithRoles() {
        String hql = " from Permission p ";
        //hql += " join fetch p.rolePermissions ";//failed to lazily initialize a collection, no session or session was closed
        //hql += " fetch all properties ";
        hql += " left join fetch p.rolePermissions rp" //
                + " left join fetch rp.permission";
        return (List<Permission>) dao.list(hql, -1, -1);
    }

}
